<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="回收编号" prop="storeId">
        <el-input
          v-model="queryParams.storeId"
          type="number"
          placeholder="请输入回收编号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable size="small">
          <el-option v-for="status in statusOptions" :label="status.label" :value="status.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="财务状态" prop="billStatus">
        <el-select v-model="queryParams.billStatus" placeholder="请选择财务状态" clearable size="small">
          <el-option v-for="bill in billStatusOptions" :label="bill.label" :value="bill.value"/>
        </el-select>
      </el-form-item>
      <el-form-item label="机型名称" prop="modelName">
        <el-input
          v-model="queryParams.modelName"
          placeholder="请输入机型名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="机型串号" prop="modelSn">
        <el-input
          v-model="queryParams.modelSn"
          placeholder="请输入机型串号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="公司信息" prop="companyInfo">
        <el-input
          v-model="queryParams.companyInfo"
          placeholder="请输入公司信息"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="报价金额" prop="price">
        <el-input
          v-model="queryParams.price"
          type="number"
          placeholder="请输入报价金额"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="返利一" prop="priceOne">
        <el-input
          v-model="queryParams.priceOne"
          type="number"
          placeholder="请输入返利一"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="返利二" prop="priceTwo">
        <el-input
          v-model="queryParams.priceTwo"
          type="number"
          placeholder="请输入返利二"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="返利三" prop="priceThree">
        <el-input
          v-model="queryParams.priceThree"
          type="number"
          placeholder="请输入返利三"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="转账方式" prop="tranType">
        <el-select v-model="queryParams.tranType" placeholder="请选择转账方式" clearable size="small">
          <el-option v-for="pay in payTypeOptions" :label="pay.label" :value="pay.value" />
        </el-select>
      </el-form-item>

      <el-form-item label="报价师" prop="offerName">
        <el-select v-model="queryParams.offerName" placeholder="请选择报价师" filterable clearable size="small">
          <el-option
            v-for="dict in offerNameOptions"
            :key="dict.userId"
            :label="dict.nickName"
            :value="dict.userId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="快递信息" prop="expInfo">
        <el-input
          v-model="queryParams.expInfo"
          placeholder="请输入快递信息"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="回收时间">
        <el-date-picker
          size="small"
          v-model="rangeQuery.offerTime"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :unlink-panels="true"
          @change="queryOfferTimeChange"
        ></el-date-picker>
      </el-form-item>

      <el-form-item label="收货时间">
        <el-date-picker
          size="small"
          v-model="rangeQuery.offerTime"
          style="width: 340px"
          value-format="yy-MM-dd HH:mm:ss"
          type="datetimerange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :unlink-panels="true"
          @change="queryCollectTimeChange"
        ></el-date-picker>
      </el-form-item>

      <el-form-item label="登记时间">
        <el-date-picker
          size="small"
          v-model="rangeQuery.createTime"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :unlink-panels="true"
          @change="queryCreateTimeChange"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="是否打款" prop="hasPay">
        <el-select
          v-model="queryParams.hasPay"
          placeholder="请选择"
          size="small"
          @keyup.enter.native="handleQuery"
          clearable>
          <el-option :value="1" label="否" />
          <el-option :value="2" label="是" />
        </el-select>
      </el-form-item>
      <el-form-item label="创建人" prop="createBy">
        <el-input
          v-model="queryParams.createBy"
          placeholder="请输入创建人"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleInsert"
          v-hasPermi="['store:collect:add']"
        >登记</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="addsOpen = true"
          v-hasPermi="['store:collect:add']"
        >批量登记</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-plus"
          size="mini"
          :disabled="multiple"
          @click="handleAddCollect"
          v-hasPermi="['store:collect:take']"
        >生成回收</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="multiple"
          @click="audioListClick"
          v-hasPermi="['store:collect:audit']"
        >审核</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['store:collect:remove']"
        >删除</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          size="mini"
          :disabled="multiple"
          @click="handleCollectList"
          v-hasPermi="['store:collect:take']"
        >一键收货</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['store:collect:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table border v-loading="loading" :data="collectList" @selection-change="handleSelectionChange" :row-class-name="setRowClassName">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="编号" align="center" prop="storeId" width="60">
        <template slot-scope="scope">
          <span class="link-type" @click="openDetailClick(scope.row)">{{scope.row.storeId}}</span>
        </template>
      </el-table-column>
      <el-table-column label="详情" align="center" width="160">
        <template v-slot="scope">
            <el-tooltip placement="top" effect="light">
              <div slot="content">
                <div>公司: {{scope.row.companyInfo}}</div>
                <div>机型: {{scope.row.modelName}}</div>
                <div>IMEI: {{scope.row.modelSn}}</div>
              </div>
              <div style="text-align: left;cursor: pointer;">
                <div class="table-row">公司: {{scope.row.companyInfo}}</div>
                <div class="table-row">机型: {{scope.row.modelName}}</div>
                <div class="table-row">IMEI: {{scope.row.modelSn}}</div>
              </div>
            </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="报价金额" align="center" prop="price" width="80" />
      <el-table-column label="返利" align="center" width="130">
        <template v-slot="scope">
          <div style="text-align: left;cursor: pointer">
            <div class="fl-row">
              一: {{scope.row.priceOne}}
              元({{thanPrice(scope.row.priceOne, scope.row.price)}})
            </div>
            <div class="fl-row">
              二: {{scope.row.priceTwo}}
              元({{thanPrice(scope.row.priceTwo, scope.row.price)}})
            </div>
            <div class="fl-row" style="border-bottom: 1px solid #000000">
              三: {{scope.row.priceThree}}
              元({{thanPrice(scope.row.priceThree, scope.row.price)}})
            </div>
            <div>合计: {{Number(scope.row.priceOne) + Number(scope.row.priceTwo) + Number(scope.row.priceThree)}} 元</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="快递费" align="center" width="100">
        <template v-slot="scope">
          <div v-if="scope.row.status <= 3">
            <el-input
              v-model="scope.row.expPrice"
              type="number" style="width: 80px;"
              @keyup.native.enter="expPriceChange(scope.row)"
            />
          </div>
          <div v-else>
            {{scope.row.expPrice}}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="合计" align="center" width="60">
        <template slot-scope="scope">
          <span style="color: red">{{rowTotal(scope.row)}}</span>
        </template>
      </el-table-column>
      <el-table-column label="报价师" align="center" prop="offerName" width="150" :formatter="offerNameFormat" show-overflow-tooltip />
      <el-table-column label="回收时间" align="center" prop="offerTime" width="100">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.offerTime, '{y}-{m}-{d}') }}</span>
          <div v-if="scope.row.status === 3">
            <span>{{"距今: " + getDayTime(scope.row) + " 天"}}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="登记时间" align="center" prop="createTime" width="100">
        <template v-slot="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status" width="80">
        <template slot-scope="scope">
          <el-tag v-for="status in statusOptions" :type="status.tagType" v-if="scope.row.status === status.value">{{status.label}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="财务状态" align="center" prop="billStatus" width="80">
        <template slot-scope="scope">
          <el-tag v-for="bill in billStatusOptions"
                  :type="bill.tagType" v-if="scope.row.billStatus === bill.value">{{bill.label}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="是否打款" align="center" prop="hasPay" width="80">
        <template slot-scope="scope">
          <el-tag type="warning" v-if="scope.row.hasPay === 1">否</el-tag>
          <el-tag v-else-if="scope.row.hasPay === 2">是</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="登记耗时" align="center">
        <template v-slot="scope">
          {{scope.row.useTime}}秒
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" width="280">
        <template v-slot="scope">
          <el-tooltip placement="top" effect="light">
            <div slot="content">
              <div>{{scope.row.remark}}</div>
            </div>
            <div class="table-row">{{scope.row.remark}}</div>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="120" class-name="small-padding fixed-width" fixed="right">
        <template slot-scope="scope">
          <el-button
            v-show="scope.row.status === 1"
            size="mini"
            type="text"
            v-hasPermi="['store:collect:use']"
            icon="el-icon-s-order"
            @click="useBtnClick(scope.row)"
          >使用</el-button>
          <el-button
            v-show="scope.row.hasPay === 1 && scope.row.status !== 5"
            size="mini"
            type="text"
            v-hasPermi="['store:collect:haspay']"
            icon="el-icon-s-order"
            @click="hasPayEdit(scope.row)"
          >打款</el-button>
          <el-button
            v-show="scope.row.status === 3 || scope.row.status === 2"
            size="mini"
            type="text"
            icon="el-icon-takeaway-box"
            v-hasPermi="['store:collect:take']"
            @click="takeBtnClick(scope.row)"
          >收货</el-button>
          <el-button
            v-show="scope.row.billStatus === 1 && scope.row.status !== 5"
            size="mini"
            type="text"
            icon="el-icon-success"
            v-hasPermi="['store:collect:audit']"
            @click="audioBtnClick(scope.row)"
          >审核</el-button>
          <el-button
            v-show="scope.row.status === 4"
            size="mini"
            type="text"
            icon="el-icon-close"
            v-hasPermi="['store:collect:close']"
            @click="closeBtnClick(scope.row)"
          >关闭</el-button>
          <el-button
            v-show="scope.row.status === 2 || scope.row.status === 3"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['store:collect:edit']"
          >修改</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <el-dialog title="详情" :visible.sync="detailOpen" width="800rpx" append-to-body>
      <el-form v-if="detailInfo != null">
        <el-row>
          <el-col :span="12">
            <el-form-item label="回收编号">{{detailInfo.storeId}}</el-form-item>
            <el-form-item label="创建人">{{detailInfo.createBy}}</el-form-item>
            <el-form-item label="收货时间">{{detailInfo.collectTime}}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态">
              <el-tag v-for="status in statusOptions"
                      :type="status.tagType" v-if="detailInfo.status === status.value">{{status.label}}</el-tag>
            </el-form-item>
            <el-form-item label="登记时间">{{detailInfo.createTime}}</el-form-item>
            <el-form-item label="用户备注">{{detailInfo.userRemark}}</el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="快递信息" v-if="detailInfo.expInfo != null">{{detailInfo.expInfo}}</el-form-item>
            <el-form-item label="流程信息" v-if="detailInfo.collectInfo != null">{{detailInfo.collectInfo}}</el-form-item>
            <el-form-item label="审核信息" v-if="detailInfo.checkInfo != null">{{detailInfo.checkInfo}}</el-form-item>
            <el-form-item label="收款码" v-if="detailInfo.payScan != null"><el-image style="width: 60%;" :src="getImageUrl(detailInfo.payScan)" /></el-form-item>
            <el-form-item label="店员码" v-if="detailInfo.clerkId != null"><el-image style="width: 60%;" :src="clerkUserPay" /></el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-dialog>
    <!-- 添加或修改门店回收对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="机型名称" prop="modelId">
              <el-select filterable remote placeholder="请输入商品关键字" @change="goodsChange"
                         v-model="form.modelId" :remote-method="getShareGoodsOptions">
                <el-option v-for="(good, key) in shareGoodsOptions"
                           :key="key"
                           :label="good.goodsName"
                           :value="good.goodsId" />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="机型名称">
              <el-input v-model="form.modelName" placeholder="请输入机型名称" />
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="机型串号">
              <el-input v-model="form.modelSn" placeholder="请输入机型串号" />
            </el-form-item>
          </el-col>
        </el-row>

       <el-row>
         <el-col :span="8">
           <el-form-item label="公司">
             <el-select v-model="optionForm.company" placeholder="请选择公司" filterable clearable size="small">
               <el-option
                 v-for="supplier in supplierList"
                 :label="supplier.supplierName" :value="supplier.supplierId" />
             </el-select>
           </el-form-item>
         </el-col>
         <el-col :span="8">
           <el-form-item label="门店">
             <el-select v-model="optionForm.store" filterable placeholder="请选择门店" size="small" @change="storeSelChange">
               <el-option
                 v-for="(store, key) in storeList"
                 :label="store.storeName" :value="key" />
             </el-select>
             <span style="color: rgba(0,0,0,0.4);font-size: 10px;">注：请在提示没有该店员时选择此项！</span>
           </el-form-item>
         </el-col>
         <el-col :span="6">
           <el-form-item label="店员">
             <el-select placeholder="请选择店员" allow-create filterable v-model="optionForm.clerk" size="small" @change="clerkChange">
               <el-option
                 v-for="(clerk,key) in clerkOptions"
                 :label="clerk.clerkName"
                 :value="key" />
             </el-select>
           </el-form-item>
         </el-col>
         <el-col :span="2">
           <el-form-item label-width="10px">
             <el-button type="primary" plain size="mini" @click="addClerk">添加</el-button>
           </el-form-item>

         </el-col>
       </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="返利公式">
              <el-select v-model="formulaIndex" style="width: 100%" filterable clearable @change="formulaInfoChange">
                <el-option v-for="(formula, index) in formulaOptions"
                           :label="formula.formulaName" :value="index" />
              </el-select>
            </el-form-item>
            <el-form-item label="报价金额" prop="price">
              <el-input-number v-model="form.price" placeholder="请输入报价金额" @change="priceChange" />
            </el-form-item>
            <el-form-item label="返利一" prop="priceOne">
              <el-input-number v-model="form.priceOne" placeholder="请输入返利一" />
              <span style="margin-left: 10px;color: #bbbbbb" v-if="formulaInfo != null">{{formulaInfo.formulaOne}}</span>
            </el-form-item>
            <el-form-item label="返利二" prop="priceTwo">
              <el-input-number v-model="form.priceTwo" placeholder="请输入返利二" />
              <span style="margin-left: 10px;color: #bbbbbb" v-if="formulaInfo != null">{{formulaInfo.formulaTwo}}</span>
            </el-form-item>
            <el-form-item label="返利三" prop="priceThree">
              <el-input-number v-model="form.priceThree" placeholder="请输入返利三" />
              <span style="margin-left: 10px;color: #bbbbbb" v-if="formulaInfo != null">{{formulaInfo.formulaThree}}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="公司信息" prop="companyInfo">
              <el-input v-model="form.companyInfo" :disabled="true" placeholder="请输入公司信息" />
            </el-form-item>
            <el-form-item label="转账方式" prop="tranType">
              <el-select v-model="form.tranType" placeholder="请选择转账方式">
                <el-option v-for="pay in payTypeOptions" :label="pay.label" :value="pay.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="报价师" prop="offerName">
              <el-select v-model="form.offerName" filterable placeholder="请选择报价师">
                <el-option
                  v-for="dict in offerNameOptions"
                  :key="dict.userId"
                  :label="dict.nickName"
                  :value="dict.userId"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="回收时间" prop="offerTime">
              <el-date-picker clearable size="small"
                              v-model="form.offerTime"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="选择回收时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="快递信息" prop="expInfo">
              <el-input v-model="form.expInfo" placeholder="请输入快递新增" />
            </el-form-item>
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!--批量回收-->
    <collect-add-list
      :offer-name-options="offerNameOptions"
      :open="addsOpen"
      @close="addsOpen = false"
      @flush="getList"
      :formula-options="formulaOptions"
      :supplier-list="supplierList"
    />
  </div>
</template>

<script>
import {
  listCollect,
  getCollect,
  delCollect,
  addCollect,
  updateCollect,
  exportCollect,
  useCollectStatus,
  takeCollectStatus,
  closeCollectStatus,
  audioCollectBillStatus,
  takeCollectStatusByList,
  audioBillStatusList,
  updateHayPay
} from "@/api/store/collect";
import {listFormula} from "@/api/store/formula"
import {listShareGoods} from "@/api/share/goods";
import {listSupplier} from "@/api/basic/supplier";
import {listStore} from "@/api/basic/store";
import {listClerk, addClerk} from "@/api/basic/clerk"
import $const from "@/utils/websocket/ServerPath";
import {getClerk_user} from "@/api/store/clerk_user";
import CollectAddList from "@/views/store/collect/collect-add-list.vue";
import {listUser} from "@/api/system/user";
export default {
  name: "Collect",
  components: {
    CollectAddList
  },
  data() {
    return {
      addsOpen: false,
      clerkUserPay: '',
      // 时间区间选项
      rangeQuery: {
        offerTime: [],
        createTime: []
      },
      //店员列表
      clerkOptions: [],
      // 门店列表
      storeList: [],
      //供应商
      supplierList: [],
      //共享模块的商品信息
      shareGoodsOptions: [],
      //门店选择数据
      optionForm: {},
      formulaIndex: null,
      //价格合计开关
      dataOpen: false,
      /* 返利公式*/
      formulaOptions: [],
      //选中的返利公式
      formulaInfo:null,
      //详情信息和开关
      detailInfo: null,
      detailOpen: false,
      payTypeOptions:[
        {label:'支付宝',value:1, tagType: ''},
        {label: '微信',value: 2, tagType: 'success'},
        {label: '银行卡',value: 3, tagType: 'warning'}],
      billStatusOptions: [
        {label:'待审核',value: 1, tagType: ''},
        {label: '已审核',value: 2, tagType: 'success'}
      ],
      statusOptions: [
        {label: '可用',value:1, tagType: ''},
        {label: '待发货',value: 2, tagType: 'warning'},
        {label: '待收货',value: 3, tagType: 'danger'},
        {label: '已收货',value: 4, tagType: 'success'},
        {label: '关闭',value: 5, tagType: 'info'}
      ],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 门店回收表格数据
      collectList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,

      // 报价师字典
      offerNameOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        storeId: null,
        status: null,
        billStatus: null,
        modelName: null,
        modelSn: null,
        expInfo: null,
        companyInfo: null,
        price: null,
        priceOne: null,
        priceTwo: null,
        priceThree: null,
        tranType: null,
        tranName: null,
        offerName: null,
        offerTime: null,
        collectTime: null,
        hasPay: null,
        createBy: null,
        params: {}
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {}
    };
  },
  created() {
    this.getList();
    listUser({roleKey:'quote'}).then(res => {
      this.offerNameOptions = res.rows;
    })
    this.getFormulaList();
    this.getSupplierList();
    this.getStoreList();
    this.getClerkOptions();
  },
  methods: {
    /*计算百分比*/
    thanPrice(m,d) {
      let res = 0;
      if(Number(m) === 0) {
        res = 0
      }
      if(Number(d) === 0) {
        res = 0
      }
      res = Number(m) / Number(d) * 100;
      return parseInt(res) + "%";
    },
    hasPayEdit(row) {
      this.$confirm('是否确认已经打款 ' + row.storeId + "?",'警告', {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        return updateHayPay(row.storeId)
      }).then(res => {
        this.msgSuccess("操作成功！");
        this.getList();
      })

    },
    getImageUrl(url) {
      console.log(url);
      console.log($const.WORK_SERVER)
      return $const.APP_SERVER + url;
    },
    getDayTime(row) {
      let long = new Date().getTime();
      let offer = new Date(row.offerTime).getTime();
      return ((long - offer) / (1000 * 60 * 60 * 24)).toFixed(0);
    },
    /** 生成回收数据*/
    handleAddCollect() {
      let supplierName = ""
      const storeIds = this.ids;
      for(let i = 0; i < storeIds.length; i++) {
        for(let j = 0; j < this.collectList.length; j++) {
          if(storeIds[i] === this.collectList[j].storeId) {
            if(this.collectList[j].status === 1 || this.collectList[j].status === 5) {
              this.msgError("数据状态不能为: 可用/关闭")
              return
            }
            let str = this.collectList[j].companyInfo.split(" ")[0];
            if(supplierName === "") {
              supplierName = str;
            }else {
              if(supplierName !== str) {
                this.msgError("请选择同一个供货商的数据！");
                return;
              }
            }
          }
        }
      }
      this.$confirm("确认生成供应商为（"+ supplierName +"）, 数量是（"+ storeIds.length +"）条的回收数据吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        let supplierId = null;
        for(let i = 0; i < this.supplierList.length; i++) {
          if(supplierName === this.supplierList[i].supplierName) {
            supplierId = this.supplierList[i].supplierId;
            break;
          }
        }
        let query = {
          collectSource: 1, //收货来源
          sourceId: supplierId,
          collectNum: storeIds.length,
          storeIds: JSON.stringify(storeIds)
        }
        return takeCollectStatusByList(query);
      }).then(resp => {
        this.getList();
        this.msgSuccess("操作成功！");
      })
    },
    /** 设置行背景颜色 */
    setRowClassName(data) {
      if(data.row.createTime == null) {
        return '';
      }
      if(data.row.status !== 3) {
        return '';
      }
      const oneDay = 1000 * 60 * 60 * 24; //一天的时间
      let newDate = new Date();
      let longTime = newDate.getTime() - new Date(data.row.createTime).getTime();
      let day = longTime / oneDay;
      if(day >= 9) {
        return 'bg_red';
      }else if(day >= 6) {
        return 'bg_yellow';
      }else if(day >= 3) {
        return 'bg_green';
      }else {
        return "";
      }
    },
    queryCreateTimeChange(e) {
      if(e == null) {
        this.$delete(this.queryParams.params, 'startTime');
        this.$delete(this.queryParams.params,'endTime');
      }else {
        this.queryParams.params["startTime"] = e[0];
        this.queryParams.params["endTime"] = e[1];
      }
    },
    //收货时间
    queryCollectTimeChange(e) {
      if(e == null) {
        this.$delete(this.queryParams.params, "collectTimeStart");
        this.$delete(this.queryParams.params, "collectTimeEnd");
      }else {
        this.queryParams.params["collectTimeStart"] = e[0];
        this.queryParams.params["collectTimeEnd"] = e[1];
      }
    },
    //搜索报价时间选择事件
    queryOfferTimeChange(e) {
      if(e == null) {
        this.$delete(this.queryParams.params, 'offerStartTime');
        this.$delete(this.queryParams.params, 'offerEndTime');
      }else {
        this.queryParams.params["offerStartTime"] = e[0];
        this.queryParams.params["offerEndTime"] = e[1];
      }
    },
    /** 店员选择事件*/
    clerkChange(e) {
      if(typeof e === "string") {
        this.msgInfo("没有该店员，如需添加入库，请先选择门店！");
      }else {
        let str = this.clerkOptions[e].clerkName.replaceAll(" ", "");
        str = this.getCompanyPrefix(this.clerkOptions[e].storeId) + " " + str;
        this.form.companyInfo = str;
        if(this.clerkOptions[e].blackGrade != null) {
          this.msgError("注意注意，该店员存在黑名单等级（"+ this.clerkOptions[e].blackGrade +"）！！！")
        }
      }
    },
    getCompanyPrefix(storeId) {
      let resp = "";
      for (let i = 0; i < this.storeList.length; i++) {
        if(this.storeList[i].storeId === storeId) {
          resp = this.storeList[i].storeName.replaceAll(" ", "");
          for(let j = 0; j < this.supplierList.length; j++) {
            if(this.storeList[i].supplierId === this.supplierList[j].supplierId) {
              let s = this.supplierList[j].supplierName.replaceAll(" ", "");
              resp = s + " " + resp;
              break
            }
          }
          break
        }
      }
      return resp;
    },
    /** 获取店员列表*/
    getClerkOptions() {
      listClerk({}).then(resp => {
        this.clerkOptions = resp.rows;
      })
    },
    //门店选择事件
    storeSelChange(e) {
      this.optionForm.company = this.storeList[e].supplierId;
    },
    /** 查询门店列表 */
    getStoreList() {
      listStore().then(resp => {
        this.storeList = resp.rows;
      })
    },
    /** 新增店员*/
    addClerk() {
      if(this.optionForm.store == null || this.optionForm.store === '') {
        this.$message({ showClose: true, message: "请选择门店", type: "warning" });
        return
      }
      let params = {
        clerkName: this.optionForm.clerk,
        storeId: this.storeList[this.optionForm.store].storeId
      }
      addClerk(params).then(resp => {
        this.getClerkOptions();
        this.msgSuccess("添加成功！")
        this.form.companyInfo = this.getCompanyPrefix(params.storeId) + " " + params.clerkName;
      })
    },
    /** 获取长期供应商列表 */
    getSupplierList() {
      let param = {longTerm: 2}
      listSupplier(param).then(resp => {
        this.supplierList = resp.rows;
      })
    },
    /** 商品模型选择事件*/
    goodsChange(e) {
      for(let i = 0; i < this.shareGoodsOptions.length; i++) {
        if(e === this.shareGoodsOptions[i].goodsId) {
          this.form.modelName = this.shareGoodsOptions[i].goodsName;
          break;
        }
      }
    },
    /** 共享模块商品信息 */
    getShareGoodsOptions(e) {
      listShareGoods({goodsName: e}).then(resp => {
        this.shareGoodsOptions = resp.rows;
      })
    },
    /* 价格*/
    expPriceChange(row) {
      updateCollect(row).then(res => {
        this.getList();
        this.msgSuccess("操作成功！");
      })
    },
    //行合计
    rowTotal(row) {
      let num = 0;
      if(row.price > 0) {
        num += row.price;
      }
      if(row.priceOne > 0) {
        num += row.priceOne;
      }
      if(row.priceTwo > 0) {
        num += row.priceTwo;
      }
      if(row.priceThree > 0) {
        num += row.priceThree;
      }
      if(row.expPrice > 0) {
        num += Number(row.expPrice);
      }
      return num;
    },
    //统计关
    closeData() {
      this.dataOpen = false;
    },
    //公式改变事件
    formulaInfoChange(e) {
      if(e == null || e === "") {
        this.form.priceOne = 0;
        this.form.priceTwo = 0;
        this.form.priceThree = 0;
        this.formulaInfo = null;
        return;
      }
      this.formulaInfo = this.formulaOptions[e];
      if(this.form.price != null) {
        this.priceChange(this.form.price);
      }
    },
    //价格改变事件
    priceChange(e) {
      if(this.formulaInfo != null) {
        this.form.priceOne = this.priceFormula(this.formulaInfo.formulaOne, e);
        this.form.priceTwo = this.priceFormula(this.formulaInfo.formulaTwo, e);
        this.form.priceThree = this.priceFormula(this.formulaInfo.formulaThree, e);
      }
    },
    //返利计算
    priceFormula(formula, price) {
      if(formula == null || formula === '') {
        return 0;
      }
      let arr = formula.split(",");
      for(let i = 0; i < arr.length; i++) {
        let count = arr[i].substring(0, 1);
        let num = arr[i].substring(1);
        switch (count) {
          case '*':
            price = parseFloat((parseFloat(price) * parseFloat(num)).toFixed(2));break;
          case '/':
            price = parseFloat((parseFloat(price) / parseFloat(num)).toFixed(2));break;
          case '+':
            price = (parseFloat(price) * 100 + parseFloat(num) * 100) / 100;break;
          case '-':
            price = (parseFloat(price) * 100 - parseFloat(num) * 100) / 100;break;
          default:
            price = 0;
            this.msgError("计算方式有误！(" + arr[i] + ")");
        }
      }
      return price.toFixed(0);
    },
    /** 获取计算公式列表*/
    getFormulaList() {
      listFormula({}).then(resp => {
        this.formulaOptions = resp.rows;
      })
    },
    audioListClick() {
      const ids = this.ids;
      if (ids == null || ids.length === 0) {
        return
      }
      this.$confirm("确定审核 " + ids.length + " 条数据吗?", "提示", {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then( () => {
        return audioBillStatusList(ids);
      }).then( res => {
        this.getList();
        this.msgSuccess("操作成功！");
      })
    },
    audioBtnClick(row) {
      this.$confirm('确定审核 '+ row.storeId +' 数据了吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return audioCollectBillStatus(row.storeId);
      }).then(resp => {
        this.getList();
        this.msgSuccess("操作成功！");
      })
    },
    closeBtnClick(row) {
      this.$confirm('确定关闭 '+row.storeId+' 数据了吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return closeCollectStatus(row.storeId);
      }).then(resp => {
        this.getList();
        this.msgSuccess("操作成功！");
      })
    },
    takeBtnClick(row) {
      this.$confirm('确定收到物品了吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return takeCollectStatus(row.storeId);
      }).then(resp => {
        this.getList();
        this.msgSuccess("操作成功！");
      })
    },
    //批量收货
    async handleCollectList() {
      const storeIds = this.ids;
      await storeIds.forEach(item => {
        takeCollectStatus(item);
      })

      this.getList();
      this.msgSuccess("操作成功！");
    },
    /** 使用按钮事件*/
    useBtnClick(row) {
      this.$confirm('确认使用吗？ 请复制: ' + row.storeId, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type:'warning'
      }).then(() => {
        return useCollectStatus(row.storeId)
      }).then(resp => {
        this.getList();
        this.msgSuccess("操作成功！")
      })
    },
    /** 打开详情窗口*/
    openDetailClick(row) {
      this.detailInfo = row;
      this.detailOpen = true;
      if(this.detailInfo.clerkId != null) {
        getClerk_user(this.detailInfo.clerkId).then(res => {
          this.clerkUserPay = this.getImageUrl(res.data.payScan);
        })
      }
    },
    /** 查询门店回收列表 */
    getList() {
      this.loading = true;
      listCollect(this.queryParams).then(response => {
        this.collectList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 报价师字典翻译
    offerNameFormat(row, column) {
      if(row.offerName === "合计") {
        return "合 计";
      }
      let str = "";
      this.offerNameOptions.forEach(item => {
        if(item.userId === Number(row.offerName))
          str = item.nickName;
      })
      return str;
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        storeId: null,
        status: 0,
        createBy: null,
        createTime: null,
        billStatus: 1,
        modelName: null,
        modelSn: null,
        expInfo: null,
        companyInfo: null,
        price: null,
        priceOne: null,
        priceTwo: null,
        priceThree: null,
        tranType: 2,
        tranName: null,
        offerName: null,
        offerTime: null,
        collectInfo: null,
        checkInfo: null,
        remark: null,
        modelId: null,
        expPrice: null,
        useTime: 0
      };
      this.optionForm = {
        company: null,
        store: null,
        clerk: null,
        shareGoodsId: null
      }
      // this.resetForm("form");
      this.formulaIndex = null;
      this.formulaInfo = null;
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
      this.closeData();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.rangeQuery = {
        offerTime: [],
        createTime: []
      }
      this.queryOfferTimeChange(null);
      this.queryCreateTimeChange(null);
      this.queryCollectTimeChange(null);
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.storeId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    handleInsert() {
      this.reset();
      this.form.useTime = new Date();
      this.open = true;
      this.title = "门店回收登记";
      this.form.offerTime = new Date();
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const storeId = row.storeId || this.ids
      getCollect(storeId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "回收编号 " + row.storeId;
        this.form.offerName = Number(this.form.offerName);
        if(this.form.offerTime == null) {
          this.form.offerTime = new Date();
        }
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.storeId != null) {
            updateCollect(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            const l = new Date().getTime();
            const  o = this.form.useTime.getTime();
            this.form.useTime = (l - o) / 1000;
            addCollect(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const storeIds = row.storeId || this.ids;
      this.$confirm('是否确认删除门店回收编号为"' + storeIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delCollect(storeIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有门店回收数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportCollect(queryParams);
        }).then(response => {
          this.download(response.msg);
        })
    },
    /** 数据转换*/
    supplierDataFormat(dataList, supplierName) {
      for(let i = 0; i < dataList.length; i++) {
        if(supplierName === dataList[i].supplierName) {
          return {
            number: dataList[i].number,
            price: dataList[i].price
          }
        }
      }
      return {number: 0, price: 0}
    },

    tableRowClassName({row, rowIndex}) {
        if(rowIndex === (this.realTimeForm.length - 1)) {
          return "bg_green";
        }
    }
  }
};
</script>

<style>
.el-table .bg_red {
  color: red;
}

.el-table .bg_yellow {
  color: #E6A23C;
}

.el-table .bg_green {
  color: green;
}
.table-row {
  white-space: nowrap;
  overflow: hidden;
}
.fl-row {
  line-height: 15px;
}
</style>
